<?php

namespace App\Listeners;

use App\Events\WechatAuth;
use App\Model\User;
use Carbon\Carbon;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class UpdateUser
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  WechatAuth  $event
     * @return void
     */
    public function handle(WechatAuth $event)
    {
        $userInfo = app('wechat')->user->get($event->openId);

        if($userInfo->subscribe == 1){
            $user = User::withTrashed()->updateOrCreate(['open_id' => $event->openId], [
                'subscribed_at' => Carbon::createFromTimestamp($userInfo->subscribe_time)->toDateTimeString(),
                'nickname' => $userInfo->nickname,
                'avatar' => $userInfo->headimgurl
            ]);
            $user->restore();
        }else{

            $user = User::withTrashed()->firstOrCreate(['open_id' => $event->openId]);

            $user->delete();

        }
        \Auth::guard('wechat')->login($user);
    }
}
